package MultithreadingTest;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName TaskQueue
 * @Description TODO
 * @Author ZhaoKai
 * @Date 2021-12-2009:20
 * @Version 1.0
 **/
public class TaskQueue2 {
    private final Lock lock = new ReentrantLock();
    private final Condition cond = lock.newCondition();
    Queue<String> queue = new LinkedList<>();

    public void addTask(String s) {
        lock.lock();
        try {
            this.queue.add(s);
            cond.signalAll();
        } finally {
            lock.unlock();
        }
    }


    public String getTask() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                cond.await();
            }
            return queue.remove();
        } finally {
            lock.unlock();
        }

    }
}
